package logic

import (
	"context"
	"shop-manager/internal/do"
	"shop-manager/internal/repos/person"
	"shop-manager/internal/vo"

	"github.com/samber/lo"
)

//go:generate newc
type PersonLogic struct {
	personRepo *person.PersonRepo
}

func (l *PersonLogic) CreatePerson(ctx context.Context, req vo.CreatePersonReq) (*vo.CreatePersonRsp, error) {
	id, err := l.personRepo.Create(ctx, &do.Person{
		Name: req.Name,
		Note: req.Note,
		Type: req.Type,
	})
	if err != nil {
		return nil, err
	}

	return &vo.CreatePersonRsp{
		ID: id,
	}, nil
}

type ListPersonRsp struct {
	Items []*vo.ListPersonRspItem
	Total int64
}

// list
func (l *PersonLogic) ListPerson(ctx context.Context, req vo.ListPersonReq) (*ListPersonRsp, error) {
	listData, total, err := l.personRepo.List(ctx, person.ListParam{
		IDs:        req.IDs,
		Page:       req.Page,
		PageSize:   req.PageSize,
		Search:     req.Search,
		Sorts:      req.Sorts,
		PersonType: req.PersonType,
	})
	if err != nil {
		return nil, err
	}

	retItems := lo.Map(listData, func(item *do.Person, index int) *vo.ListPersonRspItem {
		return &vo.ListPersonRspItem{
			ID:          item.ID,
			Name:        item.Name,
			Note:        item.Note,
			Type:        item.Type,
			TypeDisplay: item.Type.String(),
		}
	})

	return &ListPersonRsp{
		Items: retItems,
		Total: total,
	}, nil
}
